package com.edgclub.edg.task;

import android.content.Context;
import android.os.Looper;
import android.util.Log;

import com.android.volley.VolleyError;
import com.edgclub.edg.Constant;
import com.edgclub.edg.api.ResultCode;
import com.edgclub.edg.api.TopicApi;
import com.edgclub.edg.api.UploadApi;
import com.edgclub.edg.api.param.PostsParam;
import com.edgclub.edg.constant.BBConstant;
import com.edgclub.edg.event.BroadCastEvent;
import com.edgclub.edg.event.EventBus;
import com.edgclub.edg.http.VolleyListener;
import com.edgclub.edg.http.async.AsyncHttpResponseHandler;
import com.edgclub.edg.model.PostsAlbum;
import com.edgclub.edg.model.PostsAlbumData;
import com.edgclub.edg.utils.util.BitmapUtility;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.JsonUtil;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.hyphenate.easeui.model.TopicImageInfo;
import com.squareup.otto.ThreadEnforcer;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import cz.msebera.android.httpclient.Header;

/**
 * 发送图片的服务
 */
public class GzTopicImageUpload {

    private Context mContext;

    private TopicApi topicApi;
    private UploadApi uploadApi;
    private ArrayList<TopicImageInfo> infos;
    private ArrayList<PostsAlbum> postsAlbums;

    public GzTopicImageUpload(Context mContext, ArrayList<TopicImageInfo> infos) {
        super();
        this.mContext = mContext;
        this.infos = infos;
        uploadApi = new UploadApi(mContext);
        topicApi = new TopicApi(mContext);
        postsAlbums = new ArrayList<>();
        upload(0);

    }

    public void upload(final int num) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.i("infos", "-------------" + infos.size());
                Looper.prepare();
                try {
                    setnum(num);
                } catch (Exception e) {

                }
                Looper.loop();
            }
        }).start();
    }

    private void setnum(int i) {
        if (infos != null && i < infos.size()) {
            TopicImageInfo info = infos.get(i);
            if (info.getUploadstate().equals("false")) {
                try {
                    if (info.name.contains(BBConstant.URL_VOICE_PROTOCOL)) {
                        uploadApi.beginUploadTopicVoice(new File(
                                        info.getPath()), info.getTopicId(), String.valueOf(info.getPosition()), (int) info.getTime(),
                                new UploadImageHandler(info, i));
                    } else {
                        String pic0 = info.getPath();
                        String userImageFileName = Constant.TOPICIMAGEPATH
                                + pic0.hashCode();
                        if (pic0.endsWith("png") && info.getIsOri().equals("false")) {
                            BitmapUtility.compressPNGFromBitmap(pic0, userImageFileName, 300);
                        } else if ((pic0.endsWith("jpg") || pic0.endsWith("jpeg")) && info.getIsOri().equals("false")) {
                            BitmapUtility.compressImage(pic0, userImageFileName);
                        } else {
                            BitmapUtility.compressImage80(pic0, userImageFileName);
//                        userImageFileName = pic0;
                        }
                        uploadApi.beginUploadTopicAlbum(new File(
                                        userImageFileName), info.getTopicId(), String.valueOf(info.getPosition()), info.getIsOri(),
                                new UploadImageHandler(info, i));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 上传相册回调
     */
    class UploadImageHandler extends AsyncHttpResponseHandler {

        private TopicImageInfo info;
        private int num;

        public UploadImageHandler(TopicImageInfo info, int num) {
            this.info = info;
            this.num = num;
        }

        @Override
        public void onStart() {
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            try {
                String recString = new String(responseBody, "UTF-8");
                Log.e("recString" + num, recString);
                if (JSONHelper.isSuccess(recString)) {
                    PostsAlbumData data = JsonUtil.getMode(recString, PostsAlbumData.class);
                    if (!info.name.contains(BBConstant.URL_VOICE_PROTOCOL)) {
                        postsAlbums.add(data.getData());
                    }
                    upload(num + 1);
                    String pic1 = info.getPath();
                    String userImageFileName = Constant.TOPICIMAGEPATH
                            + pic1.hashCode();
                    File file = new File(userImageFileName);
                    if (file.exists()) {
                        file.delete();
                    }
                    info.setUploadstate("true");
                    boolean isend = false;
                    for (TopicImageInfo info1 : infos) {
                        if (info1.getUploadstate().equals("false")) {
                            isend = false;
                            break;
                        }
                        isend = true;
                    }
                    if (isend) {
                        topicImageFinish(info);
                    }
                } else {
                    Log.d("error:", recString + "---------------");
                    HashMap<String, Object> hashMap = new HashMap<String, Object>();
                    hashMap.put("event", BroadCastEvent.TOPICCREATEUPLOADIMG);
                    hashMap.put("issuccess", "false");
                    EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON, ThreadEnforcer.MAIN).post(hashMap);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            try {
                if (null != responseBody && responseBody.length > 0) {
                    String recString = new String(responseBody, "UTF-8");
                    Log.d("error", error.toString() + "--------------" + recString);
                }
                HashMap<String, Object> hashMap = new HashMap<String, Object>();
                hashMap.put("event", BroadCastEvent.TOPICCREATEUPLOADIMG);
                hashMap.put("issuccess", "false");
                EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON, ThreadEnforcer.MAIN).post(hashMap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    private void topicImageFinish(TopicImageInfo info) {
        PostsParam postsParam = new PostsParam();
        postsParam.setUserId(new UserPrefUtils(mContext).getUser().getId());
        postsParam.setPostsId(info.getTopicId());
        topicApi.imageFinish(postsParam, new FinishPosts(info));
    }

    /**
     * 发布贴子的监听
     */
    class FinishPosts implements VolleyListener {

        private TopicImageInfo info;


        public FinishPosts(TopicImageInfo info) {
            super();
            this.info = info;
        }

        @Override
        public void onStart(String tag) {

        }

        @Override
        public void onSuccess(String response, String tag) {
            if (JSONHelper.isSuccess(response)) {
                HashMap<String, Object> hashMap = new HashMap<String, Object>();
                hashMap.put("event", BroadCastEvent.TOPICCREATEUPLOADIMG);
                hashMap.put("issuccess", "true");
                hashMap.put("albums", postsAlbums);
                EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON, ThreadEnforcer.MAIN).post(hashMap);
                Log.i("test", "model.deleteModel");

            } else {
                HashMap<String, Object> hashMap = new HashMap<String, Object>();
                hashMap.put("event", BroadCastEvent.TOPICCREATEUPLOADIMG);
                hashMap.put("issuccess", "false");
                EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON, ThreadEnforcer.MAIN).post(hashMap);
            }
        }

        @Override
        public void onFaile(VolleyError volleyError, String tag) {
            ResultCode.toastVolleyError(mContext, volleyError);
        }

    }

}
